package net.chery.repository;

import lombok.extern.slf4j.Slf4j;
import net.chery.entity.VehProduce;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.*;
import java.util.function.Function;

/**
 * @author gai
 * @description battery_pack_entity
 * @date 2024-04-17
 */
@Repository
public interface VehProduceRepository extends JpaRepository<VehProduce, String> {
    Logger logger= LoggerFactory.getLogger(VehProduceRepository.class);
    /**
     * createTime查询
     *
     * @param createTime 创建时间
     * @return 数据
     */
    @Query("select vp from VehProduce vp where vp.createTime>?1 or vp.produceCreateTime>?1 or vp.saleCreateTime>?1")
    List<VehProduce> findByCreateTimeGreaterThan(Date createTime);

    /**
     * 获取所有未上报数据
     *
     * @param createTime 创建时间
     * @return 数据
     */
    @Query(nativeQuery = true,value = "select *\n" +
            "from sys_veh_produce\n" +
            "where (\n" +
            "          (type in (1, 3, 5, 7, 9, 11, 13, 15) and produce_create_time <= ?1 and\n" +
            "           (sync_state = '0' or (need_sh = '1' and sync_state_sh = '0')))\n" +
            "              or\n" +
            "          (type in (2, 3, 6, 7, 10, 11, 14, 15) and sale_create_time <= ?1 and\n" +
            "           (sale_sync_state = '0' or (need_sh = '1' and sale_sync_state_sh = '0')))\n" +
            "          )")
    List<VehProduce> findUnSyncData(Date createTime);

    @Override
    default <S extends VehProduce> List<S> saveAll(Iterable<S> entities) {
        int x=0;
        for (S entity : entities) {
            if (entity.isNew()) {
                entity.setCreateTime(new Date());
            }
            save(entity);
            x++;
            if(x%300==0){
                logger.info("deal: {}",x);
            }
        }
        return Collections.emptyList();
    }

    /**
     * 新数据获取
     */
    default Function<String, VehProduce> getFormCache(Map<String, VehProduce> vehProduceMap) {
        return (vin) -> {
            VehProduce cache = vehProduceMap.get(vin);
            if (cache == null) {
                cache = this.findById(vin).orElse(new VehProduce());
                cache.setVin(vin);
                vehProduceMap.put(vin,cache);
            }
            return cache;
        };
    }
}
